﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Percolation.Gui
{
    public partial class EditProbabilityForm : Form
    {
        public EditProbabilityForm(double probability)
        {
            InitializeComponent();
            Probability = probability;
        }

        public double Probability { get; private set; }

        private void m_okButton_Click(object sender, EventArgs e)
        {
            if (validateProbability())
            {
                DialogResult = System.Windows.Forms.DialogResult.OK;
                Close();
            }
        }

        private void EditProbabilityForm_Load(object sender, EventArgs e)
        {
            m_probabilityTextBox.Text = Probability.ToString();
            validateProbability();
        }

        private void m_cancelButton_Click(object sender, EventArgs e)
        {
            DialogResult = System.Windows.Forms.DialogResult.Cancel;
            Close();
        }

        private bool validateProbability()
        {
            double probability = 0.0;
            try
            {
                probability = System.Convert.ToDouble(m_probabilityTextBox.Text);
                if (isProbabilityValid(probability))
                {
                    Probability = probability;
                    m_errorProvider.SetError(m_probabilityTextBox, "");
                    return true;
                }
                
                m_errorProvider.SetError(m_probabilityTextBox, "Probability value is invalid (should be greater or equal than 0 and less or equal than 1)");
                return false;
            }
            catch (Exception)
            {
                m_errorProvider.SetError(m_probabilityTextBox, "You entered some non-digit symbols");
                return false;
            }
        }

        private bool isProbabilityValid(double probability)
        {
            return 0 <= probability && probability <= 1;
        }
    }
}
